package net.guerlab.mall.seller.print.printer;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PrintHelper {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(PrintHelper.class);

    public static void printOffline(net.guerlab.mall.seller.print.entity.offline.OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        
        print(new OfflinePrintableImpl(orderInfo));
    }

    public static void printOrder(net.guerlab.mall.seller.print.entity.order.OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        
        print(new OrderPrintableImpl(orderInfo));
    }
    
    private static void print(Printable printable) {
        if (printable == null) {
            return;
        }

        Book book = new Book();

        PageFormat pageFormat = getPageFormat();

        book.append(printable, pageFormat);

        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(book);

        try {
            job.print();
        } catch (PrinterException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }

    private static PageFormat getPageFormat() {
        PageFormat pageFormat = new PageFormat();
        pageFormat.setOrientation(PageFormat.PORTRAIT);

        Paper paper = new Paper();
        paper.setSize(getPoint(56), getPoint(297));
        paper.setImageableArea(0, 0, getPoint(56), getPoint(297));

        pageFormat.setPaper(paper);

        return pageFormat;
    }

    public static final int getPoint(int mm) {
        return (int) (mm / 25.4 * 72);
    }
}